package cn.stu.cms.config.interceptor;

import cn.hutool.core.util.StrUtil;

import cn.stu.cms.dto.UsersDto;
import cn.stu.cms.util.JwtHelper;
import cn.stu.cms.util.UserHolder;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.stu.cms.common.CommonConstants.TOKEN;
import static cn.stu.cms.util.JwtHelper.checkToken;


/**
 * 刷新令牌拦截器
 *
 * @author gh
 * @date 2023/09/19
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取请求头中的token
        String token = request.getHeader(TOKEN);
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //判断tokenKey是否存在
        if (!checkToken(token)) {
            //不存在，跳过此拦截器
            return true;
        }
        Long userId = JwtHelper.getUserId(token);
        if (userId == null) {
            return true;
        }
        //将数据存为UserDTO
        UsersDto user = new UsersDto();
        user.setUserId(userId);
        //存在，保存用户信息到 ThreadLocal
        UserHolder.saveUser(user);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
